package com.example.healkep.MainActivity;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.example.healkep.R;
import com.example.healkep.auth.HealthKitAuthActivity;
import com.huawei.hmf.tasks.OnFailureListener;
import com.huawei.hmf.tasks.OnSuccessListener;
import com.huawei.hmf.tasks.Task;
import com.huawei.hms.hihealth.ActivityRecordsController;
import com.huawei.hms.hihealth.HiHealthActivities;
import com.huawei.hms.hihealth.HiHealthStatusCodes;
import com.huawei.hms.hihealth.HuaweiHiHealth;
import com.huawei.hms.hihealth.data.ActivityRecord;
import com.huawei.hms.hihealth.data.DataType;
import com.huawei.hms.hihealth.data.Field;
import com.huawei.hms.hihealth.data.SamplePoint;
import com.huawei.hms.hihealth.data.SampleSet;
import com.huawei.hms.hihealth.options.ActivityRecordReadOptions;
import com.huawei.hms.hihealth.result.ActivityRecordReply;

import org.json.JSONArray;

import java.text.DateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.concurrent.TimeUnit;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


public class MainActivityShowSports extends Activity {

    private int[] day_food = new int[3];

    private String id = com.example.healkep.LoginActivity.getUser();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate ( savedInstanceState );
        setContentView ( R.layout.activity_show_sports );
        final TextView date = findViewById ( R.id.date );
        Button button2 = findViewById ( R.id.login );
        Button button1 = findViewById ( R.id.choose );
//绑定监听事件
        date.setText(LocalDate.now().toString());
        Calendar calendar = Calendar.getInstance();
        date.setOnClickListener((i)->{
            new DatePickerDialog(MainActivityShowSports.this, (view, year, month, dayOfMonth) -> {
                LocalDate date1 = LocalDate.of(year, month+1, dayOfMonth);
                date.setText(date1.toString());
            },calendar.get(Calendar.YEAR),calendar.get(Calendar.MONTH),calendar.get(Calendar.DAY_OF_MONTH)).show();
        });
        button1.setOnClickListener ( new View.OnClickListener () {
            @Override
            public void onClick(View view) {
                new Thread ( new Runnable () {
                    @Override
                    public void run() {
                        try {
                            String finaldate = date.getText ().toString ();
                            System.out.println ( finaldate );
                            final String json ="{\n" +
                                    "    \"user\":\""+id+"\",\n" +
                                    "    \"cdate\":\""+finaldate+"\"\n" +
                                    "}";
                            OkHttpClient client = new OkHttpClient ();  //创建http客户端
                            Request request = new Request.Builder (  )
                                    .url ( com.example.healkep.LoginActivity.url+"/sport/day" )
                                    .post ( RequestBody.create ( MediaType.parse ( "application/json"),json  ) )
                                    .build ();
                            Response response = client.newCall ( request ).execute ();  //执行发送的指令
                            String responseData = response.body ().string ();
                            JSONArray jsonArray = new JSONArray ( responseData );
                            Arrays.fill(day_food, 0);
                            for (int i = 0; i < jsonArray.length (); i++) {
                                if (jsonArray.getJSONObject(i).getInt("time_slot") == 1)
                                    day_food[0]= day_food[0] + (int)(jsonArray.getJSONObject(i).getDouble("cal") );
                                if (jsonArray.getJSONObject(i).getInt("time_slot") == 2)
                                    day_food[1]= day_food[1] + (int)(jsonArray.getJSONObject(i).getDouble("cal") );
                                if (jsonArray.getJSONObject(i).getInt("time_slot") == 3)
                                    day_food[2]= day_food[2] + (int)(jsonArray.getJSONObject(i).getDouble("cal") );

                            }
                            System.out.println ( "day_food: " );
                            System.out.println ( day_food[0] );
                            System.out.println ( day_food[1] );
                            System.out.println ( day_food[2] );
                            runOnUiThread ( new Runnable () {
                                @Override
                                public void run() {
                                    Toast.makeText ( MainActivityShowSports.this, "信息获取成功", Toast.LENGTH_SHORT ).show ();

                                }
                            } );
                        } catch (Exception e) {
                            e.printStackTrace ();
                            runOnUiThread ( new Runnable () {
                                @Override
                                public void run() {
                                    Toast.makeText ( MainActivityShowSports.this, "网络连接失败", Toast.LENGTH_SHORT ).show ();
                                }
                            } );
                        }
                    }
                } ).start ();
            }
        } );

        button2.setOnClickListener ( new View.OnClickListener () {
            @Override
            public void onClick(View view) {
                final ActivityRecordsController activityRecordsController = HuaweiHiHealth.getActivityRecordsController(MainActivityShowSports.this);
                LocalDate date1 = LocalDate.parse(date.getText().toString());
                Calendar cal = Calendar.getInstance();
                cal.set(date1.getYear(),date1.getMonthValue()-1,date1.getDayOfMonth(),0,0);
                long startTime = cal.getTimeInMillis();
                cal.add(Calendar.DAY_OF_YEAR,1);
                long endTime = cal.getTimeInMillis();
                ActivityRecordReadOptions readOption =
                        new ActivityRecordReadOptions.Builder().setTimeInterval(startTime, endTime, TimeUnit.MILLISECONDS)
                                .readActivityRecordsFromAllApps()
                                .read(DataType.DT_CONTINUOUS_CALORIES_BURNT_TOTAL)
                                .build();
                Task<ActivityRecordReply> getTask = activityRecordsController.getActivityRecord(readOption);
                getTask.addOnSuccessListener(new OnSuccessListener<ActivityRecordReply>() {
                    @Override
                    public void onSuccess(ActivityRecordReply activityRecordReply) {
                        // 打印查询到的运动记录列表
                        List<ActivityRecord> activityRecordList = activityRecordReply.getActivityRecords();
                        for (ActivityRecord activityRecord : activityRecordList) {
                            if (activityRecord == null) {
                                continue;
                            }
                            if(activityRecord.getActivityType().equals(HiHealthActivities.WALKING) ||
                                    activityRecord.getActivityType().equals(HiHealthActivities.HIKING)||
                                    activityRecord.getActivityType().equals(HiHealthActivities.INDOOR_WALK)){
                                for(SamplePoint point : activityRecord.getActivitySummary().getDataSummary()){
                                    if(point.getDataType().equals(DataType.DT_CONTINUOUS_CALORIES_BURNT_TOTAL)){
                                        day_food[0] += point.getFieldValue(Field.FIELD_CALORIES_TOTAL).asDoubleValue();
                                    }
                                }
                            }else if(activityRecord.getActivityType().equals(HiHealthActivities.YOGA)){
                                for(SamplePoint point : activityRecord.getActivitySummary().getDataSummary()){
                                    if(point.getDataType().equals(DataType.DT_CONTINUOUS_CALORIES_BURNT_TOTAL)){
                                        day_food[1] += point.getFieldValue(Field.FIELD_CALORIES_TOTAL).asDoubleValue();
                                    }
                                }
                            }else{
                                for(SamplePoint point : activityRecord.getActivitySummary().getDataSummary()){
                                    if(point.getDataType().equals(DataType.DT_CONTINUOUS_CALORIES_BURNT_TOTAL)){
                                        day_food[2] += point.getFieldValue(Field.FIELD_CALORIES_TOTAL).asDoubleValue();
                                    }
                                }
                            }
                        }
                        // 给bnt1添加点击响应事件
                        Intent intent2 = new Intent ( MainActivityShowSports.this, MainActivityShowSportsDay.class );
                        Bundle bun = new Bundle ();
                        bun.putIntArray("day_food", day_food);
                        intent2.putExtras ( bun );
                        //启动
                        startActivity ( intent2 );
                    }
                }).addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(Exception e) {
                        String errorCode = e.getMessage();
                        String errorMsg = HiHealthStatusCodes.getStatusCodeMessage(Integer.parseInt(errorCode));
                        if(Integer.parseInt(errorCode) == 50005){
                            Toast.makeText(MainActivityShowSports.this,"尚未授权",Toast.LENGTH_SHORT).show();
                            Intent intent2 = new Intent ( MainActivityShowSports.this, HealthKitAuthActivity.class );
                            startActivity(intent2);
                        }
                    }
                });

            }
        } );

    }
    @Override
    protected  void onResume() {
        super.onResume();
        Arrays.fill(day_food, 0);
    }
}
